<template>
  <view
    class="index_box"
    @touchmove="refresh.moveTouchendHandler"
    @touchstart="refresh.startTouchendHandler"
    @touchend="refresh.endTouchendHandler"
  >
    <!-- 顶部导航栏 -->
    <top-navigation-bar :roll-distance="rollDistance" />

    <!-- 轮播图 -->
    <carousel :height="500" :list-data="carouselList" />

    <!-- 房源数据列表 -->
    <view
      class="content"
      v-for="(item, index) in availabilityData"
      :key="index"
    >
      <availability-list :data="item" />
    </view>

    <!-- 加载状态 -->
    <load
      v-if="availabilityData.length > 0"
      :status="loadStatue"
      :isImage="availabilityData.length < 1"
    />
  </view>

  <!-- 下拉刷新 -->
  <pull-down-refresh
    :opacity="refresh.moveBottom.value / 3"
    :enble-anim="refresh.isRefresh.value"
  />

  <!-- 自定义tabBar导航栏 -->
  <tabBar />
</template>

<script setup lang="ts">
import { refreshHandler } from '@/components/common/pull_down_refresh/index'
import availabilityList from '@/components/layout/availability_lisit/availability-list.vue'
import carousel from '@/components/layout/carousel/carousel.vue'
import { ReqSelectPageByCommunity } from '@/api/region'
import topNavigationBar from '@/components/business/top_navigation_bar/top-navigation-bar.vue'
import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import type {
  Availability,
  Carousel,
  PageByCommunity,
  QueryPageByCommunity,
} from '@/config/data/data'
import { ref, watch } from 'vue'
import { useRegionStore } from '@/store/region'

/**
 * 当前页面滚动距离
 */
const rollDistance = ref(0)

/**
 * 房源数据列表
 */
const availabilityData = ref<Availability[]>([])

//下拉刷新控制函数
const refresh = refreshHandler(300)

/**
 * 轮播图数据列表
 */
const carouselList = ref<Carousel[]>([
  {
    img: 'https://www.lyzhnb.top/waxl/classify/%E4%BA%BA%E5%A3%B0.jpg',
    path: '',
    typed: 'image',
  },
  {
    img: 'https://www.lyzhnb.top/waxl/classify/%E5%BF%83%E6%83%85.jpg',
    path: '',
    typed: 'image',
  },
  {
    img: 'https://www.lyzhnb.top/waxl/classify/%E6%B5%B7%E6%B5%AA.jpg',
    path: '',
    typed: 'image',
  },
])

//请求是否结束
const isReq = ref(true)

//加载状态
const loadStatue = ref(1)

//对内容数据列表进行分组
const groupBy = (array: PageByCommunity[]) => {
  array.forEach((item) => {
    //是否
    let index = availabilityData.value.findIndex(
      (s) => s.village == item.village
    )
    if (index != -1) {
      availabilityData.value[index].houseList.push({
        street: item.street,
        district: item.street,
        img: item.image,
        price: item.price < item.discount ? item.price : item.discount,
        regionId: item.regionId,
      })
    } else {
      availabilityData.value.push({
        community: item.community,
        village: item.village,
        houseList: [
          {
            street: item.street,
            district: item.street,
            img: item.image,
            price: item.price < item.discount ? item.price : item.discount,
            regionId: item.regionId,
          },
        ],
      })
    }
  })
}

//区域全局状态
const region = useRegionStore()

//分页参数
const pageQuery = ref<QueryPageByCommunity>({
  page: 0,
  size: 10,
  district: '',
  place: '',
})

//监听区域全局状态,当所选的社区变更时，重新获取数据
watch(
  () => region.placeList[region.placeIndex],
  (newValue, oldValue) => {
    if (newValue) {
      uni.showLoading({
        title: '切换中...',
        mask: true,
      })
      pageQuery.value.district = region.regionList[region.regionIndex]
      pageQuery.value.place = region.placeList[region.placeIndex]
      //区域变更重新初始化房源数据
      pageQuery.value.page = 0
      nextData(true).finally(() => {
        setTimeout(() => {
          uni.hideLoading()
        }, 200)
      })
    }
  }
)

//监听下拉刷新状态
watch(
  () => refresh.isRefresh.value,
  (newValue, oldValue) => {
    if (newValue) {
      //开启刷新，并请求
      pageQuery.value.page = 0
      region.init().finally(() => {
        nextData(true).finally(() => {
          refresh.refreshEnd(500)
        })
      })
    }
  }
)

/**
 * 下一页
 * @param refresh 是否刷新
 * @return 返回一个Promise标识请求结束
 */
const nextData = (refresh: boolean = false) => {
  return new Promise((reslove) => {
    //上个请求并未结束,或者 已经没有更多 同时不是刷新状态下
    if ((!isReq.value || loadStatue.value == -1) && !refresh) {
      reslove(true)
      return
    }
    pageQuery.value.page += 1
    isReq.value = false
    loadStatue.value = 0
    //请求
    ReqSelectPageByCommunity(pageQuery.value)
      .then((res) => {
        //如果每次查询的条数等于查询条件的查询个数，表明还有下一页
        if (res.code == 200 && res.data) {
          refresh ? (availabilityData.value = []) : ''
          groupBy(res.data)
          let bool = res.data.length == pageQuery.value.size
          loadStatue.value = bool ? 1 : -1
        }
      })
      .catch(() => {
        loadStatue.value = -2
        setTimeout(() => {
          loadStatue.value = -1
        }, 100)
      })
      .finally(() => {
        //请求结束
        isReq.value = true
        reslove(true)
      })
  })
}

//监听页面是否滑动到底部
onReachBottom(() => {
  if (!isReq.value) {
    return
  }
  //加载下一页数据
  nextData()
})

//监听页面滚动
onPageScroll((e: any) => {
  //最大滚动距离不为40
  if (e.scrollTop < 40) {
    rollDistance.value = parseInt(e.scrollTop)
  }
  //如果小于5则进行赋值,标识此时是否可进行下拉刷新
  if (e.scrollTop < 5) {
    refresh.rollDistance.value = parseInt(e.scrollTop)
  }
})

//页面加载
onLoad(() => {})
</script>

<style scoped lang="scss">
.index_box {
  width: 100%;
  min-height: 100vh;
  background-color: $uni-bg-color-grey;

  .content {
    padding: 20rpx;
    width: calc(100% - 40rpx);
  }
}
</style>
